package com.aerozhonghuan.logisticsmall.modules.sort;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.PopupWindow;

import com.aerozhonghuan.foundation.base.BaseFragment;
import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.foundation.log.LogUtil;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.DB.DBAdapter;
import com.aerozhonghuan.logisticsmall.modules.common.entity.GoodsObject;
import com.aerozhonghuan.logisticsmall.modules.common.event.TabNumberChangedEvent;
import com.aerozhonghuan.logisticsmall.modules.common.event.UserInfoChangedEvent;
import com.aerozhonghuan.logisticsmall.modules.home.AddProductToGouwuche;
import com.aerozhonghuan.logisticsmall.modules.home.ChangeProductGouwucheNum;
import com.aerozhonghuan.logisticsmall.modules.home.logic.HomePageInfoRequest;
import com.aerozhonghuan.logisticsmall.modules.common.event.UserInfoChangedSuccessEvent;
import com.aerozhonghuan.logisticsmall.modules.home.search.ProductListAdapter;
import com.aerozhonghuan.logisticsmall.modules.home.search.beans.SearchBean;
import com.aerozhonghuan.logisticsmall.modules.sort.beans.TreeBean;
import com.aerozhonghuan.logisticsmall.modules.sort.logic.SortInfoRequest;
import com.aerozhonghuan.logisticsmall.utils.CommunityTool;
import com.aerozhonghuan.logisticsmall.utils.StatisticsConstant;
import com.aerozhonghuan.logisticsmall.widget.ProgressDialogIndicator;
import com.aerozhonghuan.logisticsmall.widget.TitleBarView;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 描述: HomeFragment
 * 作者:zhangyonghui
 * 创建日期：2017/6/20  on 上午 11:27
 */
public class SortFragment extends BaseFragment implements ExpandableListView.OnGroupClickListener, ChangeProductGouwucheNum,
        ExpandableListView.OnChildClickListener, AbsListView.OnScrollListener, AddProductToGouwuche {

    public static final String TAG = SortFragment.class.getSimpleName();
    public static SortFragment sSortFragment;
    private SparseArray<ArrayList<GoodsObject>> mSmallCategoryProductsArray = new SparseArray<ArrayList<GoodsObject>>();
    private PopupWindow mBrandPopupWindow;
    private View rootView;
    private TitleBarView titleBar;
    private ExpandableListView mExpandableListView;
    private GridView mProductGridView;
    private DBAdapter mDbAdapter;
    private Dialog mLoadingDialog;
    private ProductBrandAdapter mProductBrandAdapter;
    private ArrayList<String> mBrandNameList = new ArrayList<String>();
    private int mSmallCategoryID;
    private int mBrandClickPosition = -1;
    private Animation mScaleBigAnim;
    private int mScreenWidth;
    private int mScreenHeight;
    private SparseArray<ArrayList<GoodsObject>> mBigCategoryProductsSparseArray = new SparseArray<ArrayList<GoodsObject>>();
    private ProductListAdapter mProductListAdapter;
    private ProductCategoryExpandableAdapter mExpandableAdapter;
    private int mCategoryId;
    private int mLastIndex = 0;
    private ArrayList<TreeBean.Data> pCategoryEntities;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusManager.register(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_sort, null);
            initView();
            initData();
        }
        return rootView;
    }

    private void initView() {
        sSortFragment = this;
        titleBar = (TitleBarView) rootView.findViewById(R.id.titlebarview1);
        titleBar.enableBackButton(false);
        titleBar.setTitle(getResources().getString(R.string.string_tab_sort));
        mExpandableListView = (ExpandableListView) rootView.findViewById(R.id.expandablelistview);
        mExpandableListView.setOnGroupClickListener(this);
        mExpandableListView.setOnChildClickListener(this);
        mProductGridView = (GridView) rootView.findViewById(R.id.product_gridview);
        mProductGridView.setOnScrollListener(this);
        mDbAdapter = new DBAdapter(getActivity());
        mLoadingDialog = CommunityTool.getInstance().createLoadingDialog(getActivity(), "");
        mLoadingDialog.setCancelable(true);
        mLoadingDialog.setCanceledOnTouchOutside(false);
        mProductBrandAdapter = new ProductBrandAdapter(getActivity());
        mBrandPopupWindow = new PopupWindow(getActivity());
        mScreenWidth = CommunityTool.getInstance().getScreenWH(getActivity(), 0);
        mScreenHeight = CommunityTool.getInstance().getScreenWH(getActivity(), 1);
        mScaleBigAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.favorit_anim);
        initAdapterData();
    }

    private void initData() {
        SortInfoRequest.tree(getActivity(), new ProgressDialogIndicator(getActivity()), new CommonCallback<TreeBean>() {
            @Override
            public void onSuccess(TreeBean messsageBodyObject, CommonMessage commonMessage, String allResponseString) {
                if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
                    mLoadingDialog.dismiss();
                }
                pCategoryEntities = messsageBodyObject.datalist;
                if (pCategoryEntities == null || pCategoryEntities.size() == 0) {
                    return;
                }

                if (mCategoryId == 0) {
                    mCategoryId = pCategoryEntities.get(0).cid;
                }
                mExpandableAdapter.setData(pCategoryEntities);
                mExpandableListView.expandGroup(mLastIndex);
                mExpandableAdapter.setSelectedChildItem(mLastIndex, 0);
                mExpandableAdapter.notifyDataSetChanged();
                if (null != pCategoryEntities.get(mLastIndex).childs) {
                    mSmallCategoryID = pCategoryEntities.get(mLastIndex).childs.get(0).cid;
                }
                queryProductListByCid(mCategoryId);
            }
        });
    }

    private void initAdapterData() {
        mExpandableAdapter = new ProductCategoryExpandableAdapter(getActivity(), mScaleBigAnim);
        mExpandableListView.setAdapter(mExpandableAdapter);

        mProductListAdapter = new ProductListAdapter(getActivity(), mDbAdapter, "product_category_activity", 4);
        mProductGridView.setAdapter(mProductListAdapter);
    }

    private void queryProductListByCid(int categoryId) {
        HomePageInfoRequest.list(categoryId + "", "100", "1", getActivity(),
                new ProgressDialogIndicator(getActivity()), new CommonCallback<SearchBean>() {
                    @Override
                    public void onSuccess(SearchBean messsageBodyObject, CommonMessage commonMessage, String allResponseString) {
                        if (messsageBodyObject == null) {
                            return;
                        }
                        ArrayList<GoodsObject> goods = messsageBodyObject.datalist;
                        goods = reSetValue(goods);
                        goods = constructSmallCategoryProductsMap(goods);
                        mBigCategoryProductsSparseArray.put(mCategoryId, goods);
                        mProductListAdapter.setData(goods);
                    }
                });
    }

    private ArrayList<GoodsObject> reSetValue(ArrayList<GoodsObject> list) {
        ArrayList<GoodsObject> gouwucheList = mDbAdapter.getAllData();
        if (gouwucheList == null || gouwucheList.size() == 0 || list == null) {
            return list;
        }
        for (GoodsObject gouwucheP : gouwucheList) {
            for (GoodsObject p : list) {
                if (gouwucheP.getPvsid() == p.getPvsid()) {
                    int intoGouwucheSize = gouwucheP.getIntoGouwucheSize();
                    p.setIntoGouwucheSize(intoGouwucheSize);
                }
            }
        }

        return list;
    }

    private ArrayList<GoodsObject> constructSmallCategoryProductsMap(ArrayList<GoodsObject> pList) {
        ArrayList<TreeBean.Child> smallCategories = pCategoryEntities.get(mLastIndex).childs;
        ArrayList<GoodsObject> allList = new ArrayList<GoodsObject>();
        if (null == smallCategories) {
            return pList;
        }
        if (null == pList) {
            return null;
        }
        for (TreeBean.Child goodsCategory : smallCategories) {
            ArrayList<GoodsObject> addList = new ArrayList<GoodsObject>();
            for (GoodsObject p : pList) {
                if (p.getCids().contains(goodsCategory.cid)) {
                    if (p.getAliasCid() == 0) {
                        p.setAliasCid(goodsCategory.cid);
                        p.setExtName(goodsCategory.name);//用extName充当分类名称
                        addList.add(p);
                        allList.add(p);
                    } else {
                        GoodsObject newProduct = constructNewProduct(p);
                        newProduct.setAliasCid(goodsCategory.cid);
                        newProduct.setExtName(goodsCategory.name);//用extName充当分类名称
                        addList.add(newProduct);
                        allList.add(newProduct);
                    }

					/*if (p.getAliasCid() != 0) {
						p.setAliasCid(goodsCategory.getCid());
						GoodsObject newProduct = constructNewProduct(p);
						addList.add(newProduct);
						allList.add(newProduct);
					}else {
						p.setAliasCid(goodsCategory.getCid());
						addList.add(p);
						allList.add(p);
					}*/

                }
            }
            mSmallCategoryProductsArray.put(goodsCategory.cid, addList);
        }
        return allList;
    }

    private GoodsObject constructNewProduct(GoodsObject product) {
        GoodsObject newProduct = new GoodsObject();
        newProduct.setAliasCid(product.getAliasCid());
        newProduct.setBaseName(product.getBaseName());
        newProduct.setBrand(product.getBrand());
        newProduct.setCids(product.getCids());
        newProduct.setDescription(product.getDescription());
        newProduct.setDiscountPrice(product.getDiscountPrice());
        newProduct.setExtDescription(product.getExtDescription());
        newProduct.setExtName(product.getExtName());
        newProduct.setGetTime(product.getGetTime());
        newProduct.setIntoGouwucheSize(product.getIntoGouwucheSize());
        newProduct.setIsCheck(product.getIsCheck());
        newProduct.setMax(product.getMax());
        newProduct.setMin(product.getMin());
        newProduct.setNumber(product.getNumber());
        newProduct.setOldPrice(product.getOldPrice());
        newProduct.setPid(product.getPid());
        newProduct.setpImageList(product.getpImageList());
        newProduct.setpNotEnough(product.getpNotEnough());
        newProduct.setPostfixName(product.getPostfixName());
        newProduct.setPrice(product.getPrice());
        newProduct.setProductExceptionInfo(product.getProductExceptionInfo());
        newProduct.setProductLeaveMsg(product.getProductLeaveMsg());
        newProduct.setProductType(product.getProductType());
        newProduct.setPvsid(product.getPvsid());
        newProduct.setQuantityAvailable(product.getQuantityAvailable());
        newProduct.setSid(product.getSid());
        newProduct.setSmallCategory(product.getSmallCategory());
        newProduct.setSpec(product.getSpec());
        newProduct.setTitle(product.getTitle());
        newProduct.setTriangle(product.getTriangle());
        newProduct.setUnit(product.getUnit());
        newProduct.setWeight(product.getWeight());
        return newProduct;
    }

    @Override
    public void onDestroy() {
        EventBusManager.unregister(this);
        super.onDestroy();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    /**
     * 显示隐藏fragment时控制轮播
     *
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {

        } else {

        }
    }

    /**
     * 用户信息发生改变
     *
     * @param e
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onEvent(UserInfoChangedSuccessEvent e) {
        if (getActivity() == null || getActivity().isFinishing())
            return;
        LogUtil.d(TAG, "收到事件: 用户信息发生改变");

    }

    @Override
    public boolean onGroupClick(ExpandableListView arg0, View arg1, int groupPosition,
                                long arg3) {
        if (mLastIndex == -1) {
            mExpandableListView.expandGroup(groupPosition);
        }
        if (mLastIndex != -1 && mLastIndex != groupPosition) {
            mExpandableListView.collapseGroup(mLastIndex);
            mExpandableListView.expandGroup(groupPosition);
        } else if (mLastIndex == groupPosition) {
            if (mExpandableListView.isGroupExpanded(groupPosition)) {
                mExpandableListView.collapseGroup(groupPosition);
            } else {
                mExpandableListView.expandGroup(groupPosition);
            }
        }
        mLastIndex = groupPosition;
        mExpandableAdapter.setSelectedGroupItem(groupPosition);
        mExpandableAdapter.setSelectedChildItem(groupPosition, 0);
        mExpandableAdapter.notifyDataSetChanged();

        TreeBean.Data category = pCategoryEntities.get(groupPosition);
        mCategoryId = category.cid;

        int isShowBrand = category.showBrand;
        String selectBrand = getActivity().getResources().getString(R.string.select_brand);
        if (mBigCategoryProductsSparseArray.get(mCategoryId) == null || mBigCategoryProductsSparseArray.get(mCategoryId).size() == 0) {
            queryProductListByCid(mCategoryId);
        } else {
            ArrayList<TreeBean.Child> smallCategories = pCategoryEntities.get(groupPosition).childs;
            if (null != smallCategories && smallCategories.size() != 0) {
                TreeBean.Child sCategory = smallCategories.get(0);
                ArrayList<GoodsObject> sGoodsObjects = mSmallCategoryProductsArray.get(sCategory.cid);
                if (sGoodsObjects != null && sGoodsObjects.size() > 0) {
                    GoodsObject p = sGoodsObjects.get(0);
                    if (p != null) {
                        mProductListAdapter.setData(mBigCategoryProductsSparseArray.get(mCategoryId));
                        int index = mBigCategoryProductsSparseArray.get(mCategoryId).indexOf(p);
                        mProductGridView.setSelection(0);
                    }
                    Set<String> setBrand = new HashSet<String>();
                    for (GoodsObject product : sGoodsObjects) {
                        String brandName = product.getBrand();
                        if (!TextUtils.isEmpty(brandName)) {
                            setBrand.add(brandName);
                        }
                    }
                } else {
                    mProductListAdapter.setData(mBigCategoryProductsSparseArray.get(mCategoryId));
                }
            } else {
                mProductListAdapter.setData(mBigCategoryProductsSparseArray.get(mCategoryId));
            }
        }
        //mProductGridView.setSelectionFromTop(0, 0);
        mProductGridView.setSelection(0);
        mBrandClickPosition = -1;
        if (null != pCategoryEntities.get(groupPosition).childs) {
            mSmallCategoryID = pCategoryEntities.get(groupPosition).childs.get(0).cid;
        }
        StatisticsConstant.getInstance().ClickActionParams(26, 110, String.valueOf(mCategoryId));
        return true;
    }

    @Override
    public boolean onChildClick(ExpandableListView arg0, View view, int groupPosition,
                                int childPosition, long arg4) {
        mExpandableAdapter.setSelectedChildItem(groupPosition, childPosition);
        mExpandableAdapter.notifyDataSetChanged();
        TreeBean.Child samllCategory2Entity = pCategoryEntities.get(groupPosition).childs.get(childPosition);
        mSmallCategoryID = samllCategory2Entity.cid;
        clickSmallCategoryAction();
        //mProductGridView.setSelection(mProductListAdapter.getPositionForSection(childPosition));
        StatisticsConstant.getInstance().ClickActionParams(26, 110, String.valueOf(mSmallCategoryID));
        return true;
    }

    private void clickSmallCategoryAction() {
        ArrayList<GoodsObject> list = mSmallCategoryProductsArray.get(mSmallCategoryID);
        if (list != null && list.size() > 0) {
            GoodsObject p = list.get(0);
            if (p != null) {
                ArrayList<GoodsObject> pList = mBigCategoryProductsSparseArray.get(mCategoryId);
                int index = pList.indexOf(p);
                if (mBrandClickPosition != -1) {
                    mProductListAdapter.setData(pList);
                    mProductGridView.setSelection(index);
                    //mProductGridView.setSelectionFromTop(index, 0);
                } else {
                    mProductGridView.setSelection(index);
                }
            }
            Set<String> setBrand = new HashSet<String>();
            for (GoodsObject product : list) {
                String brandName = product.getBrand();
                if (!TextUtils.isEmpty(brandName)) {
                    setBrand.add(brandName);
                }
            }
        }
        mBrandClickPosition = -1;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            if (mBrandClickPosition == -1) {
                int mPosition = mProductGridView.getLastVisiblePosition();
                ArrayList<GoodsObject> list = mBigCategoryProductsSparseArray.get(mCategoryId);
                if (list != null) {
                    if (mPosition >= list.size()) {
                        return;
                    }
                    GoodsObject p = list.get(mPosition);
                    //int cid = p.getCids().get(0);
                    int cid = p.getAliasCid();
                    boolean select = false;
                    if (mSmallCategoryID != cid) {
                        select = true;
                    }
                    mSmallCategoryID = cid;
                    ArrayList<TreeBean.Child> smallCategories = pCategoryEntities.get(mLastIndex).childs;
                    if (null != smallCategories) {
                        for (int i = 0; i < smallCategories.size(); i++) {
                            int smallCid = smallCategories.get(i).cid;
                            if (smallCid == cid) {
                                mExpandableAdapter.setSelect(select);
                                mExpandableAdapter.setSelectedChildItem(mLastIndex, i);
                                mExpandableAdapter.notifyDataSetChanged();
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mLoadingDialog = null;
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    @Override
    public void change(GoodsObject product) {
        if (mBrandClickPosition == -1) {
            ArrayList<GoodsObject> bigList = mBigCategoryProductsSparseArray.get(mCategoryId);
            for (GoodsObject p : bigList) {
                if (p.getPvsid() == product.getPvsid()) {
                    p.setIntoGouwucheSize(product.getIntoGouwucheSize());
                }
            }
            mProductListAdapter.setData(bigList);
        } else {
            List<GoodsObject> curList = mProductListAdapter.getListData();
            for (GoodsObject pObject : curList) {
                if (pObject.getPvsid() == product.getPvsid()) {
                    pObject.setIntoGouwucheSize(product.getIntoGouwucheSize());
                }
            }
            mProductListAdapter.setData(curList);
        }
    }

    @Override
    public void updateData(int productSize) {
        if (productSize > 0) {
            EventBusManager.post(new TabNumberChangedEvent(2, productSize));
        }
    }
}
